package com.langsin.my0628;

import com.langsin.bean.User;

import com.langsin.chenxinhao.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;

/**
 * @author 陈鑫豪
 * @version 1.0
 * @since 2022-06-28 10:32:10
 */
public class CxhTest {
    @Test
    public void testCache2() throws Exception{
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession1 = sessionFactory.openSession();
        // 第一个会话查询
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
        User user1 = mapper1.queryById(702);
        System.out.println(user1);
//        sqlSession1.close(); 必须关闭
        sqlSession1.close();

        Thread.sleep(3000);
        System.out.println("sleep stop");
        System.out.println("----------------------------------------------------");
        // 第二个会话查询
        SqlSession sqlSession2 = sessionFactory.openSession();
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        User user2 = mapper2.queryById(702);
        System.out.println(user2);
//        sqlSession2.close();
        sqlSession2.close();
    }

    @Test
    public void testCache1() throws Exception{
        /* 一级缓存 */
        InputStream stream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = builder.build(stream);
        SqlSession sqlSession = sessionFactory.openSession();
        // 查询第一次
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.queryById(702);
        System.out.println(user);

        Thread.sleep(3000);
        System.out.println("--------------------------------");
        // 同一个sqlsession 查询第二次
        User user2 = userMapper.queryById(702);
        System.out.println(user2);

    }
}
